package ex1;

/*
 * Implementation of non-reenterent read-write lock
 * used for synchronizing accesses to cells
 */
public class ReadWriteLock{

	  private int readers       = 0;
	  private int writers       = 0;
	  private int writeRequests = 0;

	  public synchronized void lockRead(){
	    while(writers > 0 || writeRequests > 0){
	    	try{
		        wait();
	         } catch(InterruptedException e){
	        	 System.out.print("WTF??? exception while waiting");
	         }
	    }
	    readers++;
	  }

	  public synchronized void unlockRead(){
	    readers--;
	    notifyAll();
	  }

	  public synchronized void lockWrite(){
	    writeRequests++;

	    while(readers > 0 || writers > 0){
	    	try{
		        wait();
	         } catch(InterruptedException e){
	        	 System.out.print("WTF??? exception while waiting");
	         }
	    }
	    writeRequests--;
	    writers++;
	  }

	  public synchronized void unlockWrite(){
	    writers--;
	    notifyAll();
	  }
	}